<template>
	<Modal
		title="商品筛选"
		:value="value"
		:width="850"
		@on-cancel="handleCancel"
	>
		<div class="ui-form-inline">
			<Form ref="form" :mode="filterForm" inline @submit.native.prevent>
	    		<FormItem label="按分类" name="cat_id">
	    			<Cascader
						v-model="filterForm.cat_id"
						:data="categoryLists"
						clearable
						change-on-select
						style="width: 220px"
					/>
	    		</FormItem>
	            <FormItem label="按品牌" name="brand_id">
	            	<Select
						v-model="filterForm.brand_id"
						filterable
						clearable
						style="width: 150px"
					>
						<Option v-for="item in brandLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
				    </Select>
	            </FormItem>
	            <FormItem label="关键词" name="keywords">
	                <Input v-model="filterForm.keywords" placeholder="请输入关键词搜索" suffix="ios-search" clearable style="width: 198px"></Input>
	            </FormItem>
	            <Button type="primary" @click="handleSearch">筛选</Button>
	    	</Form>
		</div>
		
		<Table
	    	ref="table"
	    	:data="goodsLists"
	    	:columns="columns"
	    	:loading="tableLoading"
	    	@on-selection-change="handleChangeSelection"
	    >
	    	<div class="ui-table-cell ui-flex" slot-scope="{ row }" slot="goods">
	    		<ImageCell :src="row.thumb"></ImageCell>
	            <div class="ui-flex-full" style="margin-left: 10px;">
	            	<p class="ui-ellipsis2">{{ row.sku_name }}</p>
	            	<p class="ui-ellipsis ui-text-primary">{{ handleGetSpecTexts(row) }}</p>
	            </div>
	        </div>
	        <div slot-scope="{ row }" slot="price">
	        	<ui-price :value="row.shop_price"></ui-price>
	        </div>
	    </Table>
	    <div style="margin-top: 10px; text-align: right;">
	    	<Page :total="total" show-total @on-change="handleChangePage" />
	    </div>
	    <div slot="footer">
            <Button @click="handleCancel">取消</Button>
			<Button type="primary" @click="handleSubmit">确定</Button>
        </div>
	</Modal>
</template>

<script>
import Util from '@/libs/util.js';
import ImageCell from '@/components/ImageCell/index.vue';
import SuperTable from '@/components/SuperTable.vue';
export default {
	name: 'selectGoods',
	components: {
		ImageCell,
		SuperTable
	},
	props: {
		value: {
			type: Boolean,
			default: false
		},
		selectedData: {
			type: Array,
			default: function() {
				return [];
			}
		}
	},
	data() {
		return {
			tableLoading: false,
			goodsLists: [],
			total: 0,
			brandLists: [],
			categoryLists: [],
			currentSelectData: [],		// 当前选择的
			filterForm: {
				keywords: '',
				brand_id: undefined,
				cat_id: []
			},
			params: {
				status: 1,
				keywords: '',
				cat_id: '',
				brand_id: '',
				cat_ids: '',
				brand_ids: '',
				page: 1,
				limit: 5
			},
			columns: [
				{
                    type: 'selection',
                    width: 54,
                    align: 'center'
                },
                {
                    title: '商品',
                    slot: 'goods'
                },
                {
                    title: '价格',
                    slot: 'price',
                    width: 220
                },
                {
                    title: '库存',
                    key: 'number',
                    width: 120
                }
			]
		}
	},
	computed: {
		brands() {
        	return this.$store.state.app.brands;
        },
        categories() {
        	return this.$store.state.app.categories;
        }
	},
	mounted() {
		// 获取品牌数据
    	this.$store.dispatch('getBrandData');
    	// 获取品类数据
    	this.$store.dispatch('getCategoryData');
    	
		this.init();
	},
	watch: {
		value(val) {
			if(val) {
				this.params.page = 1;
				this.params.cat_id = '';
				this.params.brand_id = '';
				this.params.keywords = '';
				this.filterForm.keywords = '';
				this.filterForm.brand_id = undefined;
				this.filterForm.cat_id = [];
				this.init();
			}
		},
		brands: {
			deep: true,
			handler() {
				if(this.brands.length > 0) {
					this.brandLists = this.brands;
				}
			}
		},
		categories: {
			deep: true,
			handler() {
				if(this.categories.length > 0) {
					this.categoryLists = this.categories;
				}
			}
		}
	},
	methods: {
		init() {
			this.tableLoading = true;
	    	Util.ajax.post(this.API['API_GOODS_SKU_LISTS'], this.params).then(res => {
	    		// 已有的数据
	    		let ids = this.selectedData.map(item => {
	    			return item.sku_id;
	    		})
	    		// 当前已选中的数据
	    		let sids = this.currentSelectData.map(item => {
	    			return item.sku_id;
	    		})
	    		
	    		this.goodsLists = res.data.map(item => {
	    			if(ids.indexOf(item.sku_id) >= 0) {
	    				item._disabled = true;
	    			}else if(sids.indexOf(item.sku_id) >= 0) {
	    				item._checked = true;
	    			}
	    			return item;
	    		});
	    		this.total = res.total;
	    		this.tableLoading = false;
	    	}).catch(() => {
	    		
	    	})
		},
		setBrand(items, ids) {
			ids = ids || [];
			if(items) {
				this.brandLists = items;
			}else{
				this.brandLists = this.brands;
			}
			this.params.brand_ids = ids.join(',');
		},
		setCategory(items, ids) {
			ids = ids || [];
			if(items) {
				this.categoryLists = items;
			}else{
				this.categoryLists = this.categories;
			}
			this.params.cat_ids = ids.join(',');
		},
		handleGetSpecTexts(row) {
			if(Array.isArray(row.spec)) {
				let texts = row.spec.map(item => {
					return item.name +':'+ item.value;
				})
				return texts.join('、');
			}else{
				return row.spec.name +':'+ row.spec.value;
			}
		},
		// 分页
		handleChangePage(page) {
			this.params.page = page;
			this.init();
		},
		// 条件搜索
		handleSearch() {
			this.params.page = 1;
			this.params.brand_id = this.filterForm.brand_id || '';
			this.params.keywords = this.filterForm.keywords;
			if(this.filterForm.cat_id.length > 0) {
				this.params.cat_id = this.filterForm.cat_id[this.filterForm.cat_id.length - 1];
			}else{
				this.params.cat_id = '';
			}
			this.init();
		},
		// 表格选中触发事件
		handleChangeSelection(selection) {
			let results = this.currentSelectData;
			let ids = this.goodsLists.map(item => {
				return item.sku_id;
			})
			
			// 清除当前已选择的数据中，当前表格页面的数据
			results = results.filter(item => {
				return ids.indexOf(item.sku_id) < 0;
			})
			
			this.currentSelectData = [...results, ...selection];
		},
		handleCancel() {
			this.$emit('input', false);
			this.currentSelectData = [];
			this.$refs.form.resetFields();
		},
		handleSubmit() {
			this.$emit('on-change', [...this.selectedData, ...this.currentSelectData]);
			this.handleCancel();
		}
	}
}
</script>